<?php
class Db{

	function __construct($db_config=''){
		global $db_config;
		$this->dbconfig = $db_config;
	}


	/** 創建DB連接與db操作類對象
	* @param String	$mode 	模式 讀/寫
	* @param String	$dbname	DbConfig DB_dbname_
	* @return dbobj,dblink
	*/
	public function addConnect($mode,$dbname=''){
		$mode = empty($dbname)? 'DB_'.$mode : 'DB_'.$dbname.'_'.$mode;

		if($dbmobj = get_instance_of('dbm',$mode)){		//判斷dbombj是否存在，存在則返回
			$dbm = $dbmobj;
		}else{
			$dbm = $this->factory($mode);
			if(!$dbm){	echo 'DB mode error!';	exit();	}
			get_instance_of('dbm',$mode,$dbm);			//記錄當前dbmobj
		}
		if($conn = get_instance_of('dblink',$mode)){	//判斷dblink是否存在,存在則返回
			$dbconn = $conn;
		}else{
			$dbconn = $dbm->connect($mode);
			get_instance_of('dblink',$mode,$dbconn);	//記錄當前dblink
		}
		return array($dbm,$dbconn);
	}


	/** 選擇DB
	* @param String $mode	DbConfig Array
	* @return dbobj
	*/
	public function factory($mode){
		if(isset($this->dbconfig[$mode])){
			$dbms = $this->dbconfig[$mode]['dbms'];
			if(in_array($dbms, array('Mysql','Mongo'))){
				require_cache(LIB_PATH.'/Db/Driver/Db'.$dbms.'.class.php');
				$dbClass = 'Db'.$dbms;
				return new $dbClass($this->dbconfig);			
			}else{
				return false;
			}			
		}else{
			return false;
		}
	}

}
?>